package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.AdminOrderMapper;
import com.sky.mapper.UserOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private AdminOrderMapper adminOrderMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;

    /**
     * 订单超时"15分钟"自动取消
     */
    @Scheduled(cron = "0 * * * * ?")
    public void OrderTimeoutHandle() {
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = adminOrderMapper.SelectOrderTimeout(Orders.PENDING_PAYMENT, dateTime);

        ordersList.forEach(item -> {
            item.setStatus(Orders.CANCELLED);
            item.setCancelReason(MessageConstant.ORDER_TIMEOUT);
            item.setCancelTime(LocalDateTime.now());

            userOrderMapper.update(item);
            log.info(MessageConstant.ORDER_TIMEOUT + ":{}", item.getNumber());
        });

    }

    /**
     * 订单自动确认收货
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void OrderAutoReceiveGoodsHandel() {
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-120);
        List<Orders> ordersList = adminOrderMapper.SelectOrderTimeout(Orders.DELIVERY_IN_PROGRESS, dateTime);

        ordersList.forEach(item -> {
            item.setStatus(Orders.COMPLETED);
            item.setDeliveryTime(LocalDateTime.now());

            userOrderMapper.update(item);
            log.info(MessageConstant.ORDER_AUTO_RECEIVE_GOODS + ":{}", item.getNumber());
        });

    }


}
